<template>
  <div class="container">
    <div class="map-wrapper">
      <div id="map"></div>
    </div>
    <div class="info-area">
      <h2>当前选择的箱变信息</h2>
      <p>箱变名称：<span>{{ chooseBoxInfo.箱变名称 }}</span></p>
      <p>X坐标：<span>{{ chooseBoxInfo.X坐标 }}</span></p>
      <p>Y坐标：<span>{{ chooseBoxInfo.Y坐标 }}</span></p>
      <p>控制器编号：<span>{{ chooseBoxInfo.控制器编号 }}</span></p>
      <p>灯杆数量：<span>{{ chooseBoxInfo.灯杆数量 }}</span></p>
      <p>备注：<span>{{ chooseBoxInfo.路段名称 }}</span></p>
      <p>备注：<span>{{ chooseBoxInfo.备注 }}</span></p>
      <div>
        <div>
          <el-button type="primary" @click="switchShowAll">查看所有</el-button>
          <el-button type="success" :disabled="!chooseBoxInfo.id" @click="switchShowChooseBox">查看已关联</el-button>
          <el-button type="danger" :disabled="!chooseBoxInfo.id" @click="clearChooseInfo">清除已选择</el-button>
        </div>
        <div style="margin-top: 5px;margin-bottom: 5px;">
          <el-button type="success" :disabled="!chooseBoxInfo.id" @click="refreshRelation">刷新已关联</el-button>
        </div>
      </div>
      <div>
        <el-table :data="chooseBoxRelationPoleInfo" style="width: 100%;height: 300px;overflow-y: auto;"
          empty-text="无数据">
          <el-table-column label="已关联灯杆id">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <el-icon>
                  <timer />
                </el-icon>
                <span style="margin-left: 10px">{{ scope.row.id }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="已关联灯杆编号">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <el-icon>
                  <timer />
                </el-icon>
                <span style="margin-left: 10px">{{ scope.row.lightPoleCode }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="danger" @click="deleteRelationPole(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-table :data="chooseBoxRelationPointInfo"
          style="margin-top: 10px;width: 100%;height: 300px;overflow-y: auto;" empty-text="无数据">
          <el-table-column label="已关联管点id">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <el-icon>
                  <timer />
                </el-icon>
                <span style="margin-left: 10px">{{ scope.row.id }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="已关联管点编号">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <el-icon>
                  <timer />
                </el-icon>
                <span style="margin-left: 10px">{{ scope.row.管线点编号 }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="danger" @click="deleteRelationPoint(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { Scene } from '@antv/l7';
import { GaodeMap } from '@antv/l7-maps';
import { PointLayer } from '@antv/l7';
import light_pole_data from '@/assets/light_pole.json';
import light_point_data from '@/assets/light_point.json';
import box_data from '@/assets/box.json';
import light_pole_img from '@/assets/light_pole.png';
import light_point_img from '@/assets/light_point.png';
import box_img from '@/assets/box.jpeg';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus'

let scene;
const chooseBoxFeuture = ref()
const chooseBoxInfo = ref({})
const chooseBoxRelationPoleInfo = ref([])
const chooseBoxRelationPointInfo = ref([])


// 灯杆图层
const lightPoleLayer = new PointLayer()
  .source(light_pole_data, {
    parser: {
      type: 'geojson',
    },
  })
  .shape('lightPoleIcon')  // 统一用这个图片
  .active({
    color: '#00FF00',  // 选中状态：红色
  })
  .select({
    color: '#00FF00',  // 选中后变红色
  })
  .size(30)
  .style({
    opacity: 1.0,
  });


// 灯杆文字图层
const lightTextLayer = new PointLayer()
  .source(light_pole_data, {
    parser: {
      type: 'geojson',
    },
  })
  .shape('灯杆编号', (val) => val)
  .size(50)
  .color('#408d84')
  .active({
    color: '#00FF00',  // 选中状态：红色
  })
  .select({
    color: '#00FF00',  // 选中后变红色
  })
  .style({
    textAnchor: 'center',
    textAllowOverlap: true,
    fontWeight: 'bold',
  });


// 当灯杆图层选中后执行操作
lightTextLayer.on('click', (e) => {
  if (!chooseBoxInfo.value.id) {
    return
  }

  const poleInfo = e.feature.properties
  axios.post('/box/relation', {
    id: poleInfo.id,
    boxInfoControlCode: chooseBoxInfo.value.控制器编号,
    boxInfoControlCodeNew: chooseBoxInfo.value.id.padStart(4, '0'),
    lightPoleCode: poleInfo.灯杆编号,
    lightPoleAlreadyCode: poleInfo.灯杆现有编号,
    x: poleInfo.X坐标,
    y: poleInfo.Y坐标,
    lightPoolAttribute: poleInfo.灯杆属性,
    lightPoolHeight: poleInfo.灯杆高度,
    lightPoolLayout: poleInfo.道路灯杆布置形式,
    lightPoolMaterial: poleInfo.灯杆材料,
    lightPoolShape: poleInfo.灯杆形状,
    lightSource: poleInfo.光源类型,
    lightPower: poleInfo.光源功率,
    lightCount: poleInfo.光源数量,
    controlMode: poleInfo.控制方式,
    buildDate: poleInfo.建成日期,
    leaveDate: poleInfo.移交时间,
    remark: poleInfo.备注,
  }).then(res => {
    if (res.data) {
      ElMessage({
        message: `灯杆编号：${poleInfo.灯杆编号},已关联箱变控制器编号：${chooseBoxInfo.value.id.padStart(4, '0')}`,
        type: 'success',
      })
    }

    if (res.data === false) {
      ElMessage({
        message: `灯杆：${poleInfo.灯杆编号},已关联箱变控制器编号：${chooseBoxInfo.value.id.padStart(4, '0')}`,
        type: 'warning',
      })
    }
  })
});
























// 照明管点图层
const lightPointLayer = new PointLayer()
  .source(light_point_data, {
    parser: {
      type: 'geojson',
    },
  })
  .shape('lightPointIcon')  // 统一用这个图片
  .active({
    color: '#00FF00',  // 选中状态：红色
  })
  .select({
    color: '#00FF00',  // 选中后变红色
  })
  .size(30)
  .style({
    opacity: 1.0,
  });

// 照明管点文字图层
const lightPointTextLayer = new PointLayer()
  .source(light_point_data, {
    parser: {
      type: 'geojson',
    },
  })
  .shape('管线点编码', (val) => val)
  .size(30)
  .color('#408d84')
  .style({
    textAnchor: 'center',
    textAllowOverlap: true,
    fontWeight: 'bold',
  });









// 当照明管点图层选中后执行操作
lightPointLayer.on('click', (e) => {
  if (!chooseBoxInfo.value.id) {
    return
  }

  const pointintInfo = e.feature.properties
  axios.post('/box/relation-point', {
    id: pointintInfo.id,
    boxInfoControlCode: chooseBoxInfo.value.控制器编号,
    boxInfoControlCodeNew: chooseBoxInfo.value.id.padStart(4, '0'),
    权属管理单位: pointintInfo.权属管理单位,
    统一社会信用代码: pointintInfo.统一社会信用代码,
    管线点编码: pointintInfo.管线点编码,
    管线点编号: pointintInfo.管线点编号,
    管线类型: pointintInfo.管线类型,
    管线类别: pointintInfo.管线类别,
    x坐标: pointintInfo.X坐标,
    y坐标: pointintInfo.Y坐标,
    坐标系: pointintInfo.坐标系,
    地面高程: pointintInfo.地面高程,
    井深: pointintInfo.井深,
    特征: pointintInfo.特征,
    附属物: pointintInfo.附属物,
    井盖规格: pointintInfo.井盖规格,
    载体: pointintInfo.载体,
    建成日期: pointintInfo.建成日期,
    投用日期: pointintInfo.投用日期,
    备注: pointintInfo.备注,
  }).then(res => {
    if (res.data) {
      ElMessage({
        message: `照明管点：${pointintInfo.管线点编号},已关联箱变控制器编号：${chooseBoxInfo.value.id.padStart(4, '0')}`,
        type: 'success',
      })
    }

    if (res.data === false) {
      ElMessage({
        message: `照明管点：${pointintInfo.管线点编号},已关联箱变控制器编号：${chooseBoxInfo.value.id.padStart(4, '0')}`,
        type: 'warning',
      })
    }
  })
});












// 箱变图层
const boxLayer = new PointLayer()
  .source(box_data, {
    parser: {
      type: 'geojson',
    },
  })
  .shape('boxIcon')  // 统一用这个图片
  .active({
    color: '#00FF00',  // 选中状态：红色
  })
  .select({
    color: '#00FF00',  // 选中后变红色
  })
  .size(30)
  .style({
    opacity: 1.0,
  });

// 当箱变图层选中后执行操作
boxLayer.on('click', (e) => {
  chooseBoxFeuture.value = e.feature
  chooseBoxInfo.value = e.feature.properties
  axios.post('/box/create', {
    id: chooseBoxInfo.value.id,
    name: chooseBoxInfo.value.箱变名称,
    x: chooseBoxInfo.value.X坐标,
    y: chooseBoxInfo.value.Y坐标,
    controlCode: chooseBoxInfo.value.控制器编号,
    codeNew: chooseBoxInfo.value.id.padStart(4, '0'),
    boxOutLineLoop: chooseBoxInfo.value.箱变出线回路,
    secondLevelPowerName: chooseBoxInfo.value.二级配电柜名称,
    loopCount: chooseBoxInfo.value.回路数,
    roadName: chooseBoxInfo.value.路段名称,
    lightPoleCount: chooseBoxInfo.value.灯杆数量,
    remark: chooseBoxInfo.value.备注,
  },
    {
      headers: {
        'Content-Type': 'application/json'
      }
    }
  ).then(res => {
    if (res.data) {
      ElMessageBox.alert(`当前已选中箱变：${chooseBoxInfo.value.id.padStart(4, '0')},接下来点击其余信息即可关联！`, `提示`, {
        confirmButtonText: '我知道了',
      })
      axios.post(`/box/relation-list/${chooseBoxInfo.value.id.padStart(4, '0')}`, {})
        .then(res => {
          chooseBoxRelationPoleInfo.value = res.data
        })
      axios.post(`/box/relation-point-list/${chooseBoxInfo.value.id.padStart(4, '0')}`, {})
        .then(res => {
          chooseBoxRelationPointInfo.value = res.data
        })
    }
  })
});














const switchShowAll = () => {
  boxLayer.setData(box_data, { parser: { type: 'geojson', } })
  lightPoleLayer.setData(light_pole_data, { parser: { type: 'geojson', } })
  lightTextLayer.setData(light_pole_data, { parser: { type: 'geojson', } })
  lightPointLayer.setData(light_point_data, { parser: { type: 'geojson', } })
  ElMessage({
    message: `已展示所有数据`,
    type: 'success',
  })
}

const switchShowChooseBox = async () => {
  if (chooseBoxFeuture.value) {
    // 切换箱变数据
    const boxShowGeoJson = {
      "type": "FeatureCollection",
      "features": [chooseBoxFeuture.value]
    }
    boxLayer.setData(boxShowGeoJson, { parser: { type: 'geojson', } })

    await refreshRelation();

    // 切换灯杆数据
    const chooseId = chooseBoxRelationPoleInfo.value.map(item => item.id)
    const chooseFeatures = light_pole_data.features.filter(data => chooseId.includes(parseInt(data.properties.id)))
    const lightPoleShowGeoJson = {
      "type": "FeatureCollection",
      "features": chooseFeatures
    }

    // 切换管点数据
    const choosePointId = chooseBoxRelationPointInfo.value.map(item => item.id)
    const choosePointFeatures = light_point_data.features.filter(data => choosePointId.includes(parseInt(data.properties.id)))
    const lightPointShowGeoJson = {
      "type": "FeatureCollection",
      "features": choosePointFeatures
    }

    lightPoleLayer.setData(lightPoleShowGeoJson, { parser: { type: 'geojson', } })
    lightTextLayer.setData(lightPoleShowGeoJson, { parser: { type: 'geojson', } })
    lightPointLayer.setData(lightPointShowGeoJson, { parser: { type: 'geojson', } })

    ElMessage({
      message: `已展示${chooseBoxFeuture.value.properties.控制器编号}的关联数据！`,
      type: 'success',
    })
  }
}

const clearChooseInfo = () => {
  chooseBoxInfo.value = {}
  chooseBoxRelationPointInfo.value = []
  chooseBoxRelationPoleInfo.value = []
  chooseBoxFeuture.value = {}
  ElMessage({
    message: `已清除已选择信息`,
    type: 'success',
  })

}

const deleteRelationPole = (row) => {
  axios.delete(`/box/relation-delete/${row.id}`)
    .then(res => {
      if (res.data) {
        axios.post(`/box/relation-list/${chooseBoxInfo.value.id.padStart(4, '0')}`, {})
          .then(res => {
            chooseBoxRelationPoleInfo.value = res.data
          })
      }
    })
}


const deleteRelationPoint = (row) => {
  axios.delete(`/box/relation-point-delete/${row.id}`)
    .then(res => {
      if (res.data) {
        axios.post(`/box/relation-point-list/${chooseBoxInfo.value.id.padStart(4, '0')}`, {})
          .then(res => {
            chooseBoxRelationPointInfo.value = res.data
          })
      }
    })
}

const refreshRelation = async () => {
  const id = chooseBoxInfo.value.id.padStart(4, '0')

  const [relationRes, pointRes] = await Promise.all([
    axios.post(`/box/relation-list/${id}`, {}),
    axios.post(`/box/relation-point-list/${id}`, {})
  ])

  chooseBoxRelationPoleInfo.value = relationRes.data
  chooseBoxRelationPointInfo.value = pointRes.data
}

onMounted(() => {
  // 场景
  scene = new Scene({
    id: 'map',
    map: new GaodeMap({
      style: 'dark',
      center: [106.396743, 29.603943],
      zoom: 11.5,
      pitch: 0,
    }),
    logoVisible: false,
    useResizeObserver: true
  });

  // 设置灯杆，照明管点icon，初始化场景
  scene.addImage('lightPoleIcon', light_pole_img);
  scene.addImage('lightPointIcon', light_point_img);
  scene.addImage('boxIcon', box_img);
  scene.on('loaded', () => {
    scene.addLayer(lightPoleLayer);
    // scene.addLayer(lightTextLayer);

    scene.addLayer(lightPointLayer);
    //scene.addLayer(lightPointTextLayer);
    scene.addLayer(boxLayer);
  });
});
</script>


<style>
html,
body,
#app {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.container {
  display: grid;
  grid-template-columns: 80% 20%;
  width: 100%;
  height: 100%;
}

.map-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
}

#map {
  width: 100%;
  height: 100%;
  display: block;
}

.info-area {
  padding: 16px;
  background: #f5f5f5;
  overflow-y: auto;
}
</style>